package com.jspgou.cms.action.front;

import static com.jspgou.cms.Constants.MEMBER_SYS;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.htmlparser.http.HttpHeader;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.jspgou.cms.WeChat;
import com.jspgou.cms.entity.Order;
import com.jspgou.cms.entity.Payment;
import com.jspgou.cms.entity.ShopPaymentorder;
import com.jspgou.cms.entity.ShopYushou;
import com.jspgou.cms.manager.OrderMng;
import com.jspgou.cms.manager.PaymentMng;
import com.jspgou.cms.manager.ShipmentsMng;
import com.jspgou.cms.manager.ShopPaymentorderMng;
import com.jspgou.cms.manager.ShopYushouMng;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.web.RequestUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;
import com.jspgou.core.web.front.FrontHelper;

/**
 * 微信支付（当前支持微信扫码支付:WeChatScanCodePayment）
 * @author Administrator
 *
 */
@Controller
public class WeChatAct extends WeChat{
	
	//支付appid   
//	public static final String APPID="wxc596191fde33119f";
//	//商户号
//	public static final String MCHId="1264316901";
//	//商户密钥
//	public static final String KEY="3jeecmszjc0791DzdJovJeecmsJeebbs";
	//同意下单接口
	
	
	//merchant_id(超市id);金额
	//在线支付订单(多个订单提交付款时{加入购物车的形式最终付款})
//	@RequestMapping(value="/weChatPay.jspx",method=RequestMethod.POST)
//	public String ordersPay(Long orderId,String code,HttpServletRequest request,HttpServletResponse response, ModelMap model) throws JDOMException{
//		Website web = SiteUtils.getWeb(request);		
//		if(orderId!=null&&shopPermentOrderMng.findById(orderId)!=null){
//			ShopPaymentorder shopPermentorder=shopPermentOrderMng.findById(orderId);
//			Payment payment=paymentMng.findByCode(code);					
//			try{
//				if(!StringUtils.isBlank(code)&&code.equals("weChatScancodePay")){
//					WeChatScanCodePayment(payment,web,shopPermentorder,request,response, model);
//				}
//			}catch(IOException e){
//				e.printStackTrace();
//			}
//		}else {
//			return FrontHelper.pageNotFound(web, model, request);
//	   }
//		return null;				
//	}	
	
	@RequestMapping(value="/WeChatReturn.jspx")
	public String WeChatScanCodePaymentReturn(HttpServletRequest request,HttpServletResponse response, ModelMap model) throws JDOMException, IOException {
		synchronized (this) {	
			//回调结果
			String xml_receive_result = getXmlRequest(request);
			System.out.println(xml_receive_result);
			Map<String, String> result_map = doXMLParse(xml_receive_result);
			String sign_receive=result_map.get("sign");
			result_map.remove("sign");
			String key=paymentMng.findByCode("weChatScancodePay").getSellerKey();
			if(key==null){
				return ShopFrontHelper.showMessage(request, model, "微信扫码支付密钥错误，请通知商户");
			}
			String checkSign=createSign(result_map,key);
			if(checkSign!=null&&checkSign.equals(sign_receive)){
				System.out.println("weixinhuidiaodizhi");
				try{
					//通知微信该订单已处理
					noticeWeChatSuccess();
					if(result_map!=null){
						String return_code=result_map.get("return_code");
						if("SUCCESS".equals(return_code)&&"SUCCESS".equals(result_map.get("result_code"))){
							System.out.println("11111111111111111111");
							String transaction_id=result_map.get("transaction_id");//微信返回的微信订单号（属于微信商户管理平台的订单号，跟自己的系统订单号不一样）
							String out_trade_no=result_map.get("out_trade_no"); //商户系统的订单号，与请求一致。
							ShopPaymentorder shopPermentorder=shopPermentOrderMng.findByCode(out_trade_no);
							//主订单改成“已支付”
							shopPermentorder.setStatus(2);
							//这里是把微信商户的订单号放入了交易号中
							shopPermentorder.setTradeno(transaction_id);
							shopPermentOrderMng.update(shopPermentorder);
							List<Order> order= manager.getPaymentOrder(shopPermentorder);
							System.out.println("222222222222222222222");
							for(int i=0;i<order.size();i++){
								//副订单改成“已支付”
								order.get(i).setPaymentStatus(2);
								order.get(i).setTradeNo(transaction_id);
								order.get(i).setPaymentCode("weChatScancodePay");
								manager.updateByUpdater(order.get(i));
							}
							System.out.println("3333333333333333333333");
							return ShopFrontHelper.showMessage(request, model, "支付成功");	
						}else if("SUCCESS".equals(return_code)&&result_map.get("err_code")!=null){
							return ShopFrontHelper.showMessage(request, model, result_map.get("err_code_des"));	
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}else{
				Map<String,String> parames=new HashMap<String,String>();
				parames.put("return_code", "FAIL");
				parames.put("return_msg", "校验错误");
				//将参数转成xml格式
				String xmlWeChat = getRequestXml(parames);
				System.out.println("fasongweixinshibaishuju==="+xmlWeChat);
				try{    		
					testPost(UNIFORM_SINGLE_INTERFACE,xmlWeChat);
				}catch(Exception e){
					e.printStackTrace();
				}
				return ShopFrontHelper.showMessage(request, model, "支付参数错误，请重新支付!");
			}
		}
        return ShopFrontHelper.showMessage(request, model, "支付错误，请重新支付!");	
	}
	
	@RequestMapping(value="/weChatPay.jspx")
	public String WeChatScanCodePayment(Integer merchant_id,Integer price,String out_trade_no,String priductName,Website web,
			HttpServletRequest request,HttpServletResponse 
			response,ModelMap model) throws JDOMException, IOException{
		String str = new String((priductName).getBytes("GBK"),characterEncoding);
		Map<String,String> paramMap = new HashMap<String,String>();  
		paramMap.put("appid", APPID); //微信分配的公众账号ID（企业号corpid即为此appId）[必填]
		paramMap.put("mch_id", MCHId); //微信支付分配的商户号 [必填]
		paramMap.put("device_info", "WEB");//终端设备号(门店号或收银设备ID)，注意：PC网页或公众号内支付请传"WEB" [非必填]
		paramMap.put("nonce_str", getWCRandomNumber(10));  //随机字符串，不长于32位。  [必填]
		paramMap.put("body", str); //商品或支付单简要描述 [必填]
		paramMap.put("out_trade_no", out_trade_no); //商户系统内部的订单号,32个字符内、可包含字母, [必填]
		paramMap.put("fee_type", "CNY"); //符合ISO 4217标准的三位字母代码，默认人民币：CNY. [非必填]
		//paramMap.put("total_fee", fromYuanToFen(price)); //金额必须为整数  单位为分 [必填]
		paramMap.put("total_fee", price.toString());
		//paramMap.put("spbill_create_ip",RequestUtils.getIpAddr(request)); //APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP [必填]
		paramMap.put("spbill_create_ip","127.0.0.1");
		//paramMap.put("notify_url", "http://"+web.getDomain()+"/WeChatReturn.jspx"); //接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。 [必填]    
		paramMap.put("notify_url", "http://www.baidu.com");
		paramMap.put("trade_type", "NATIVE"); //交易类型{取值如下：JSAPI，NATIVE，APP，(JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付)} [必填]
		paramMap.put("product_id", merchant_id.toString()); // 商品ID{trade_type=NATIVE，此参数必传。此id为二维码中包含的商品ID，商户自行定义。}
		paramMap.put("sign",createSign(paramMap,KEY));//根据微信签名规则，生成签名 
		String xmlWeChat = getRequestXml(paramMap);//把参数转换成XML数据格式   
		System.out.println(xmlWeChat);
		String resXml=testPost(UNIFORM_SINGLE_INTERFACE,xmlWeChat);
		System.out.println("resXml=="+resXml);
		Map<String, String> map = doXMLParse(resXml);
		String returnCode = map.get("return_code");
		if(returnCode.equalsIgnoreCase("FAIL")){
			return ShopFrontHelper.showMessage(request, model, map.get("return_msg"));
		}else if(returnCode.equalsIgnoreCase("SUCCESS")){
			if(returnCode.equalsIgnoreCase("SUCCESS")&&map.get("err_code")!=null){
				return ShopFrontHelper.showMessage(request, model, map.get("err_code_des"));
			}else if(returnCode.equalsIgnoreCase("SUCCESS")&&map.get("result_code").equalsIgnoreCase("SUCCESS")){				
				String code_url=map.get("code_url");
				getQRCode1(code_url,response);
				return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,WECHATPAYMENT), request);
			}
		}
		return ShopFrontHelper.showMessage(request, model, "系统超时，请重试!");
	}
	
	@Autowired
	private OrderMng manager;
	@Autowired
	private PaymentMng paymentMng;
	@Autowired
	private ShipmentsMng shipmentMng;
	@Autowired
	private ShopYushouMng yushouMng;
	@Autowired
	private ShopPaymentorderMng shopPermentOrderMng;
}
